package com.practice.reggie.service.impl.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.practice.reggie.dto.DishDTO;
import com.practice.reggie.entity.DishFlavor;
import com.practice.reggie.mapper.DishFlavorMapper;
import com.practice.reggie.service.DishFlavorService;
import com.practice.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishFlavorServiceImpl extends ServiceImpl<DishFlavorMapper, DishFlavor> implements DishFlavorService {
    @Autowired
    private DishService dishService;

    /**
     * 菜品新增保存，同时保存口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional //多次insert，使用事务控制
    public void addDishAndFlavor(DishDTO dishDTO) {
        saveOrUpdateDishAndFlavor(dishDTO, "s");
        //保存菜品的基本信息到菜品表
//        boolean save = dishService.save(dishDTO);
//        System.out.println(save);
//        //保存成功后，会自动把id回写到dishDto
//        Long id = dishDTO.getId();//菜品id
//
//        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
//        List<DishFlavor> collect = dishFlavors.stream().map(item -> {
//            item.setDishId(id);
//            return item;
//        }).collect(Collectors.toList());
//
//        //保存口味到口味表
//        boolean b = saveBatch(collect);
//        System.out.println(b);
    }

    /**
     * 菜品修改保存
     *
     * @param dishDTO
     */
    @Override
    @Transactional //开启事务
    public void updateDishAndFlavor(DishDTO dishDTO) {
        saveOrUpdateDishAndFlavor(dishDTO, "u");
    }

    //抽取公共代码
    private void saveOrUpdateDishAndFlavor(DishDTO dishDTO, String mark) {
        if ("u".equals(mark)) {
            dishService.updateById(dishDTO);
        } else {
            //保存dish表内容
            dishService.save(dishDTO);
        }
        //保存dishflavor表
        //获取dish id
        Long id = dishDTO.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //移除之前口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId, id);
        remove(queryWrapper);

        //数据处理
        List<DishFlavor> collect = flavors.stream().map(item -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //报错dishflavors
        saveBatch(flavors);
    }
}